import * as Nexus from "@nexus/schema";
import _ from "lodash";
import { fieldName, fieldDescription, inputName, payloadName } from "./config";

// 拓展类型
export default Nexus.extendType({
  // 类型
  type: "Mutation",

  // 定义
  definition(t) {
    t.field(fieldName, {
      // 描述
      description: fieldDescription,

      // 类型
      type: payloadName,

      // 参数
      args: {
        // 输入
        input: Nexus.nonNull(
          Nexus.arg({
            // 描述
            description: "输入",

            // 类型
            type: inputName,
          }),
        ),
      },

      // 解析
      resolve: async (_root, args, ctx, _info) => {
        const { input } = args;

        const { db } = ctx;

        const { password, account } = input;

        const admin = await db.admin.findUnique({
          where: { account },
          include: { store: true },
        });

        if (!admin) {
          return { code: 200, message: "fail" };
        }

        const { password: passwordHash } = admin;

        const isSame = ctx.service.encryption.comparePasswordHash(password, passwordHash);
        if (!isSame) {
          return { code: 202, message: "fail" };
        }

        const { id: adminId } = admin;

        const token = ctx.service.encryption.generateToken({ source: "CONSOLE", adminId });

        return { code: 0, message: "success", token, me: admin };
      },
    });
  },
});
